package com.huayi.order.controller;


import com.huayi.order.DataConfigObject;
import com.huayi.order.entity.ErpSalesOrderDetailVo;
import com.huayi.order.entity.ErpSalesOrderEntity;
import com.huayi.order.enums.EnumErpOrderStatus;
import com.huayi.order.service.ErpSalesOrderService;
import com.huayi.order.service.ExpressCompanyService;
import com.huayi.order.service.SalesManService;
import com.huayi.order.thymeleaf.PagingResponse;
import com.huayi.order.utils.DateUtil;
import com.huayi.order.utils.EnumResultVo;
import com.huayi.order.utils.ExportOrderListExcecl;
import com.huayi.order.utils.ResultVo;
import com.huayi.order.utils.kuaidi100.ExpressPrintResult;
import com.huayi.order.utils.kuaidi100.ExpressPrintUtils;
import com.huayi.order.utils.kuaidi100.PrintImgVo;
import com.huayi.order.utils.kuaidi100.SendVo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;

/**
 * 描述：
 *
 * @author qlp
 * @date 2019-09-24 16:05
 */
@RequestMapping("/order")
@Controller
public class SalesOrderController {
    @Autowired
    private ErpSalesOrderService salesOrderService;
    @Autowired
    private ExpressCompanyService expressCompanyService;
    @Autowired
    private SalesManService salesManService;

    /**
     * 订单列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String orderList(Model model, HttpServletRequest request) {
        model.addAttribute("menuId", "order_list");


        String page = request.getParameter("page");
        Integer pageIndex = 1;
        Integer pageSize = DataConfigObject.getInstance().getPageSize();
        String orderNum = "";
        String contactMobile = "";
        Integer startTime = 0;
        Integer endTime = 0;
        Integer saleType = null;
        Integer salesManId = null;
        Integer status = null;

        if (!StringUtils.isEmpty(page)) {
            pageIndex = Integer.parseInt(page);
        }
        if (!StringUtils.isEmpty(request.getParameter("pageSize"))) {
            try {
                pageSize = Integer.parseInt(request.getParameter("pageSize"));
            } catch (Exception e) {
            }
        }
        if (!StringUtils.isEmpty(request.getParameter("orderNum"))) {
            orderNum = request.getParameter("orderNum");
            model.addAttribute("orderNum",orderNum);
        }
        if (!StringUtils.isEmpty(request.getParameter("contactMobile"))) {
            contactMobile = request.getParameter("contactMobile");
            model.addAttribute("contactMobile",contactMobile);
        }

        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            status = Integer.parseInt(request.getParameter("status"));
            model.addAttribute("status",status);
        }

        if (!StringUtils.isEmpty(request.getParameter("salesManId"))) {
            salesManId = Integer.parseInt(request.getParameter("salesManId"));
            model.addAttribute("salesManId",salesManId);
        }

        if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
            startTime = DateUtil.dateToStamp(request.getParameter("startTime"));
            model.addAttribute("startTime",request.getParameter("startTime"));
        }
        if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
            endTime = DateUtil.dateTimeToStamp(request.getParameter("endTime") + " 23:59:59");
            model.addAttribute("endTime",request.getParameter("endTime"));
        }


        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpSalesOrderDetailVo> result = salesOrderService.getList(pageIndex, pageSize, orderNum, contactMobile, saleType, status, startTime, endTime,salesManId);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        var salesMan = salesManService.getList("","");
        model.addAttribute("salesMan",salesMan);

        return "order_list";

    }

    /**
     * 订单详情
     *
     * @param model
     * @param id      订单Id
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String getOrderDetail(Model model, @RequestParam Long id, HttpServletRequest request) {
        ErpSalesOrderDetailVo orderDetail = salesOrderService.getDetailById(id);


        model.addAttribute("order", orderDetail);
        model.addAttribute("menuId", "order_list");

        return "order_detail";
    }



    /***
     * 快递面单打印（打印页面）
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_send_express", method = RequestMethod.GET)
    public String orderSendExpress(Model model, HttpServletRequest request) {
        Long id =Long.valueOf(request.getParameter("id"));
        Integer expressId=Integer.parseInt(request.getParameter("express"));
        //查询单据
        ErpSalesOrderDetailVo order = salesOrderService.getDetailById(id);


        //查询是否已经打印过，打印过有保存快递面单信息

        if (StringUtils.isEmpty(order.getLogisticsImg())==false) {
            model.addAttribute("img", order.getLogisticsImg());
            model.addAttribute("error", "快递单号：" + order.getLogisticsCode());
        } else {

            if (order.getStatus() == EnumErpOrderStatus.WaitSend.getIndex()) {
                //设置发货地址
                SendVo sendVo = new SendVo();
                sendVo.setSendManMobile("400-800-1713");
                sendVo.setSendManName("华衣云购");
                sendVo.setSendManPrintAddr("广东省东莞市大朗镇聚新二路42号");


                PrintImgVo print = new PrintImgVo();
                //发件人信息
                print.setSendManName(sendVo.getSendManName());
                print.setSendManMobile(sendVo.getSendManMobile());
                print.setSendManPrintAddr(sendVo.getSendManPrintAddr());

                //收件人信息
                print.setRecManName(order.getContactPerson());
                print.setRecManMobile(order.getContactMobile());

                String province = "";
                String city = "";
                String area = "";
                if (StringUtils.isEmpty(order.getProvince()) == false) {
                    province = order.getProvince();
                }
                if (StringUtils.isEmpty(order.getCity()) == false) {
                    city = order.getCity();
                }
                if (StringUtils.isEmpty(order.getArea()) == false) {
                    area = order.getArea();
                }
                print.setRecManProvince(province);
                print.setRecManCity(city);
                print.setRecManDistrict(area);

                print.setRecManAddr(order.getAddress());
                print.setRecManPrintAddr(order.getAddress());
                //组合订单商品数据
                StringBuilder orderGoods = new StringBuilder();
                orderGoods.append("\r\n");
                for (var item:order.getItems()) {
                    orderGoods.append(item.getGoodsTitle());
                    orderGoods.append("[数量："+item.getQuantity()+"]");
                    orderGoods.append("\r\n");
                }
                //订单信息
                String orderDetail = "订单号：" + order.getOrderNum();
                orderDetail += orderGoods.toString();
                print.setNet("cainiao");
                print.setCargo(orderDetail);//order.getOrderDetail()
                if(expressId.intValue()==1){
                    print.setKuaidicomname("韵达快递");
                    print.setKuaidicom("yunda");
                }else if(expressId.intValue()==2){
                    print.setKuaidicomname("百世快递");
                    print.setKuaidicom("huitongkuaidi");
                }
                print.setOrderId(order.getOrderNum());
                print.setRemark("订单备注");
                //快递信息
                print.setCount(1);//件数
                print.setWeight(0.25d);//物品总重量KG
                print.setVolumn(2000d);//物品总体积，CM*CM*CM，double类
//            String img = expressService.printImg(print);

//                SysVariableEntity sysVariableEntity = systemService.getVariable(VariableEnums.URL_WMS_INDEX.name());
//                print.setPollCallBackUrl(sysVariableEntity.getValue());

                int openSubscription = 0;

                String partnerId="4398900340329";
                String partnerKey="dFVsaGlNYW1LdU0yMkx1bHR5OVJHTFJDMjdPeThSLyt1ckVNMHNDMnFjaW1VdC9Rd3doNE5wYVVsSTVHTWpqaw==";
                try {
                    Properties properties = PropertiesLoaderUtils.loadAllProperties("config.properties");
                    partnerId =properties.getProperty("partnerId");
                    partnerKey =properties.getProperty("partnerKey");
                } catch (Exception e) {
                }

                //请求接口打印快递面单
                ResultVo<ExpressPrintResult> resultVo = ExpressPrintUtils.generateExpressPrintImg(print, openSubscription,partnerId,partnerKey);

                if (resultVo.getCode() == EnumResultVo.SUCCESS.getIndex()) {
                    //更新快递面单信息
                    salesOrderService.updateLogisticsStatus(order.getId(), resultVo.getData().getKuaidinum(), resultVo.getData().getKuaidicomName(), resultVo.getData().getKuaidicom(), resultVo.getData().getImgBase64());

                    model.addAttribute("img", resultVo.getData().getImgBase64());
                } else {
                    model.addAttribute("error", resultVo.getMsg());
                }
            } else {
                model.addAttribute("error", "订单不是待发货的订单");
            }
        }
        return "order_send_express";
    }

    /***
     * 订单发货
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/order_send", method = RequestMethod.GET)
    public String orderSend(Model model, HttpServletRequest request, @RequestParam Long id) {
        //查询单据
        ErpSalesOrderDetailVo order = salesOrderService.getDetailById(id);
        model.addAttribute("order", order);

        model.addAttribute("company", expressCompanyService.getExpressCompany());

        return "order_send";
    }

    /**
     * excel导出
     *
     * @param request
     * @param response
     */
    @RequestMapping("/order_list_excel_export")
    @ResponseBody
    public void outExport(HttpServletRequest request, HttpServletResponse response) {

        String orderNum = "";
        if (!StringUtils.isEmpty(request.getParameter("orderNum"))) {
            orderNum = request.getParameter("orderNum");
        }

        String contactMobile = "";
        if (!StringUtils.isEmpty(request.getParameter("contactMobile"))) {
            contactMobile = request.getParameter("contactMobile");
        }

        Integer status = null;
        if (!StringUtils.isEmpty(request.getParameter("status"))) {
            try {
                status = Integer.parseInt(request.getParameter("status"));
            }catch (Exception e){}
        }

        Integer startTime = 0;
        Integer endTime = 0;
        if (!StringUtils.isEmpty(request.getParameter("startTime"))) {
            String startDateStr = request.getParameter("startTime");
            startTime = DateUtil.dateToStamp(startDateStr);
        }
        if (!StringUtils.isEmpty(request.getParameter("endTime"))) {
            String endDateStr = request.getParameter("endTime");
            endTime = DateUtil.dateTimeToStamp(endDateStr + " 23:59:59");
        }

        //查询订单
        var lists = salesOrderService.getOrderItemListAll(orderNum, contactMobile, null, status, startTime, endTime);


        /***************根据店铺查询订单导出的信息*****************/
        String excelFileName = "order_";//excel文件名前缀
        //创建excel
        HSSFWorkbook workbook = ExportOrderListExcecl.createExcel(excelFileName, lists);

        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((excelFileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }

        return;
    }
}
